/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dbproxy;

import com.google.gson.Gson;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.util.Arrays;

/**
 *
 * @author Miguel
 */
public class FileServer implements Runnable {
    
    private Socket sck;
    private File dirWeb;
    private LogInterface log;
    
    public FileServer(Socket sck, File dirWeb, LogInterface log) {
        this.sck=sck;
        this.dirWeb=dirWeb;
        this.log=log;
    }

    @Override
    public void run() {
        BufferedReader br=null;
        PrintWriter pw=null;
        File arch=null;        
        try {
            br=new BufferedReader(new InputStreamReader(sck.getInputStream()));
            pw=new PrintWriter(sck.getOutputStream(), true);
            String linea=br.readLine();
            log.recibirLinea("cliente: "+sck.getInetAddress().getHostName()
                    +" conectado");
            while(!linea.isEmpty()) {
                log.recibirLinea(linea);
                if(linea.contains("GET")) {
                    log.recibirLinea(linea);
                    String[] partes=linea.split(" ");
                    //String uri="file:/"+partes[1];                    
                    String archStr=partes[1];
                    //System.out.println(decode.replaceAll("(file://)(.*)", "$2"));
                    //arch=new File(dirRoot, decode.replaceAll("(file://)(.*)", "$2"));
                    if(archStr.contains("images")) {
                        arch=new File(dirWeb, archStr.substring(archStr.indexOf("/")+1));
                        log.recibirLinea("directiorio web="+arch.getAbsolutePath());
                    } else {
                        final String idProd=archStr.substring(archStr.lastIndexOf("/")+1);
                        log.recibirLinea(idProd);
                        File productsDir=new File(dirWeb, 
                                archStr.substring(archStr.indexOf("/")+1))
                                .getParentFile();
                        log.recibirLinea(productsDir.getAbsolutePath());
                        arch=productsDir.listFiles(new FileFilter() {

                            @Override
                            public boolean accept(File pathname) {                                
                                String name=pathname.getName();
                                String id=name.substring(0, name.indexOf("."));                                
                                return id.equals(idProd);
                            }
                        })[0];
                    }
                }
                linea=br.readLine();
            }            
           
            if(arch!=null && arch.exists()) {                
                int len=(int) arch.length();
                log.recibirLinea("SEND "+arch.getName());
                pw.println("SEND "+arch.getName()); 
                pw.println("length:"+len);
                pw.println();
                enviarArchivo(arch);
            }
            
            linea=br.readLine();
            while(!linea.isEmpty()) {
                if(linea.equals("RECIBIDO OK")) {
                    log.recibirLinea("Archivo "+ arch.getName()+ " enviado");
                }
                linea=br.readLine();
            }
            
        } catch (IOException ex) {
            log.recibirLinea("IOException: "+ex.getMessage());
        } finally {
            try {
                br.close();
                pw.close();
            } catch (IOException ex) {
                log.recibirLinea("IOException: "+ex.getMessage());
            } catch (NullPointerException ex ) {
                log.recibirLinea("IOException: "+ex.getMessage());
            }
        }
    }

    private void enviarArchivo(File arch) {
        FileInputStream fis=null;
        BufferedInputStream bfi=null;
        PrintWriter pw=null;        
        int bufSize=8192;
        byte buf[]=new byte[bufSize];
        Gson gs=new Gson();
        try {            
            fis=new FileInputStream(arch);
            bfi=new BufferedInputStream(fis,bufSize);
            pw=new PrintWriter(sck.getOutputStream(), true);
                      
            int leido=bfi.read(buf);
            while(leido>0) {
                byte[] newBuf= Arrays.copyOfRange(buf, 0, leido);
                String bufStr=gs.toJson(newBuf);
                pw.println(bufStr);                                
                leido=bfi.read(buf);
            }            
            pw.println();
            
            
        } catch (FileNotFoundException ex) {
            log.recibirLinea(ex.getMessage());
        } catch (IOException ex) {
            log.recibirLinea(ex.getMessage());
        }  finally {
            try {                 
                pw.close();
                bfi.close();
                fis.close();                               
            } catch (IOException ex) {
                log.recibirLinea(ex.getMessage());
            } catch (NullPointerException ex ) {
                log.recibirLinea(ex.getMessage());
            }
        } 
    }
    
}
